//项目中路由能否被访问
import router from '@/router'
import nprogress from 'nprogress'
import "nprogress/nprogress.css"
import useUserStore from '@/store/modules/user.ts'
//全局守卫:项目当中任意路由切换都会触发的钩子
//全局前置守卫
router.beforeEach(async (to: any, from: any, next: any) => {
    //to:你将要访问那个路由//from:你从来个路由而来//next:路由的放行函数
    nprogress.start()
    nprogress.configure({ showSpinner: false });
    let UserStore = useUserStore()
    let token = UserStore.token
    //用户未登录:可以访向login,其尔六个路山本能访向(指自1ogin)//用户登录成功:不可以访间10gin[指向首页],其余的路由可以访间
    if (token) {
        if (to.path === '/login') {
            next({ path: '/' })
        } else {
            //如果token还在,就重新请求;不然就是token被修改或者是过期了
            //全部路由组件:登录|464|任意路由|首页|数据大屏|权限管理(二个子路由)|商品管理(四个子路由)
            if (UserStore.userName) {

                next();
            } else {
                try {
                    //如果没有用户信息,在守卫这里发请求获取到了用户信息再放行
                    await UserStore.userInfo()
                    console.log(UserStore.userName);

                    //等动态追加路由的加载完再跳转防止空白页
                    // next({...to})

                    next({ ...to })
                } catch {
                    //token过期
                    
                    await UserStore.logOut();
                    next({ path: '/login', query: { redirect: to.path } })
                }
            }


        }
    } else {
        if (to.path === '/login') {
            next();
        } else {
            next({ path: '/login', query: { redirect: to.path } })
        }
    }
})
router.afterEach((to: any, from: any, next: any) => {
    nprogress.done()
})